package com.lagou.config;

import com.lagou.enums.SqlCommand;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration =configuration;
    }

    public void parse(InputStream inputStream) throws Exception {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        buildStatementFromContext(rootElement);

    }

    private void buildStatementFromContext(Element rootElement) throws Exception {
        String namespace=rootElement.attributeValue("namespace");
        List<Element> parseNodes = getParseNodes("select|insert|update|delete",rootElement);
        if(parseNodes!=null&&parseNodes.size()>0){
            for (Element element : parseNodes) {
                String id = element.attributeValue("id");
                String paramterType = element.attributeValue("paramterType");
                String resultType = element.attributeValue("resultType");
                String sqlText = element.getTextTrim();

                MappedStatement statement = new MappedStatement();
                statement.setId(id);
                statement.setParamterType(paramterType);
                statement.setResultType(resultType);
                statement.setSql(sqlText);
                String key=namespace+"."+id;

                SqlCommand sqlCommand=SqlCommand.convertSqlCommand(sqlText);
                statement.setSqlCommand(sqlCommand);
                configuration.getMappedStatementMap().put(key,statement);
            }
        }

    }

    private List<Element> getParseNodes(String nodeText,Element rootElement) {

        List<Element> elementList=new ArrayList<>();
        String[] nodes = nodeText.split("\\|");
        for (String node : nodes) {
            List<Element> list = rootElement.selectNodes("//" + node);
            elementList.addAll(list);
        }
        return elementList;

    }


}
